var app = getApp();
var util  = require('../../utils/util.js')
const cnConvert = require('../../utils/changefont.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        maskFalg: false,
        curDataType: {},
        curDataDate: {},
        curDataCoffeeMaker: {},
        curRanking: {},
        // 销售排行头部数据筛选数据	

        curDataTypeList: [],
        curDataDateList: [],
        curDataCoffeeMakerList: [],
        curRankingsList: [],
        RankingsList:[],
        // 加盟商排行头部数据筛选数据
        jcurDataType: {},
        jcurDataDate: {},
        jcurRanking: {},

        jcurDataTypeList: [],
        jcurDataDateList: [],
        jcurRankingsList: [],


        curSearchListIdx: 0,
        curIdx:0,
        offset:0,
        offseta:0,
        joffset:0,
        noData:false,

        AnalysisList:[],
        jiamemList:[], //加盟商数据列表
        loading: true,
        noBind:true,
        orderTotal:0,
        priceTotal:0,

        isDali:false,
        noJm:false,

        jmList:[],//加盟筛选数据列表
        cjm:{},//当前加盟商

        coffeeMakerId:0, // 联动咖啡机id

        pageText:{
          'title':'数据分析',
          'jmph':'加盟商排行',
          'xsph':'销售排行',
          'ydtj':'月度统计',
          'mysj':'没有数据',
          'spmc':'商品名称',
          'ddl':'订单量',
          'xse':'销售额',
          'cplx':'产品类型',
          'kfj':'咖啡机',
          'orderTotal': '订单合计',
          'saleTotal': '销售合计',
          'corder': '咖啡订单量',
          'gorder': '商品定单量',
          'cprice': '咖啡销售额',
          'gprice': '商品销售额',
          'totle': '合计',
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.initData();
        if (wx.getStorageSync('userDo').font == 1) { //切换繁体
          var textObj = this.data.pageText
          for (var item in textObj) {
            textObj[item] = cnConvert.traditionalized(textObj[item])
          }
          this.setData({
            pageText: textObj
          })
          wx.setNavigationBarTitle({ title: this.data.pageText.title })
        }
        
    },

    onShow:function(){
      if (wx.getStorageSync('userDo')) {
        if(wx.getStorageSync('userDo').type == 1){
          this.setData({
            isDali: true,
            curIdx:2,
          })
          if (!this.data.jiamemList.length){
            this.getJiaMengList();
          }
          this.getJiamTotal();
        }else{
          this.getTotal();
        }
        this.setData({
            noBind: false,
        })
      } else {
          this.setData({
              noBind: true,
              loading:false
          })
      }
    },
    goBind: function () {
        wx.navigateTo({
            url: '/pages/bindAccount/bindAccount',
        })
    },
    showType: function (e) {
        var idx = e.currentTarget.dataset.idx

        if (this.data.curSearchListIdx == idx) { //点击两次同样筛选条件关闭列表
            this.setData({
                maskFalg: !this.data.maskFalg,
                curSearchListIdx: idx
            })
        } else {
            this.setData({
                maskFalg: true,
                curSearchListIdx: idx
            })
        }
    },

    //获取加盟商数据筛选列表
    getJmList:function(){
      var that = this;
      return new Promise((resolve,reject) =>{
        wx.request({
          url: app.globalData.api + 'getAgentListByAgentId',
          data: {
            select: 0,
            limit: 300,
            offset: 0,
            parent: wx.getStorageSync('userDo').id,
            type: 2
          },
          success: function (res) {
            if (res.data.length) {
              resolve(res.data)
              
            }else{
              reject(res.data)
            }
          }
        })
      })
    },
    getTotal: function () {
        var that = this;
        var user = wx.getStorageSync('userDo');
        var t = ''
        if (this.data.curIdx == 1){
            t = ''
        }else{
            t = this.data.curDataDate.value || 0
        }
        wx.request({
            url: app.globalData.api + 'coffeeOrderCount',
            data: {
                makerUserId: user.userId,
                userTypee: user.type,
                saleType: that.data.curDataType.id || "",
                time: t,
                makerId: that.data.curDataCoffeeMaker.id || '',
                leagueId: that.data.cjm.userId || -1 //默认自营
            },
            success: function (res) {
                that.setData({
                    orderTotal: res.data.orderCount,
                    priceTotal: res.data.orderPay,
                })
            }
        })
    },
    closeMask: function () {
        this.setData({
            maskFalg: false,

        })
    },
   
    getItem: function (e) {
        var name = e.currentTarget.dataset.item
        var that = this;
        var i = this.data.curSearchListIdx
        if (i == 0) { //产品类型
            this.setData({
                curDataType: name
            })
        } else if (i == 1) {  //天数排行 
            this.setData({
                curDataDate: name
            })
        } else if(i == 2) { // 咖啡机排行 
            this.setData({
                curDataCoffeeMaker: name
            })
        }else{
            this.setData({
              cjm: name,
              coffeeMakerId: name.userId
            })
            this.getCoffeeMakerList(name).then(function(res){
              that.setData({
                curDataCoffeeMakerList: res,
                curDataCoffeeMaker: res[0],
              })
            })
        }
        this.setData({
            maskFalg: false,
            RankingsList:[],
            offset:0
        })
        this.getRankingsList();
        this.getTotal();      
    },
    jgetItem: function (e) {
      var name = e.currentTarget.dataset.item
      var i = this.data.curSearchListIdx
      if (i == 0) {
        this.setData({
          jcurDataType: name
        })
      } else if (i == 1) {
        this.setData({
          jcurDataDate: name
        })
      } 
      this.setData({
        maskFalg: false,
        jiamemList: [],
        noJm:false,
        joffset: 0
      })
     
      this.getJiamTotal();
      this.getJiaMengList();


    },
    tapAnalys:function(e){
        this.setData({
            curIdx: e.currentTarget.dataset.idx,
            maskFalg: false,
        })
        if (e.currentTarget.dataset.idx == 1 ){

          if (this.data.AnalysisList.length == 0){
            this.getAnalysisList();
          }                    
        }
        // 加盟商排行
        if (e.currentTarget.dataset.idx == 2){
          if (this.data.jiamemList.length == 0){
            this.getJiaMengList();
          }
          this.getJiamTotal();
         
        }else{
          this.getTotal();
        } 
    },

    getJiamTotal:function(){
      var that = this;
      wx.request({
        url: app.globalData.api + 'leagueIdOrderStatistic',
        data: {
          date: util.formatTime(new Date()).substring(0, 10),
          day: that.data.jcurDataDate.value || 0,
          agentId: wx.getStorageSync('userDo').id,
          offset: that.data.joffset,
          saleType: that.data.jcurDataType.id,
          allLeagueId: 1
        },
        success: function (res) {
          if(res.data[0]){
            that.setData({
              orderTotal: res.data[0].orderCount,
              priceTotal: res.data[0].orderPay
            })
          }
        }
      })
    },

    getJiaMengList:function(){
      var that = this;
      that.setData({
        loading:true
      })
      wx.request({
        url: app.globalData.api +'leagueIdOrderStatistic',
        data:{
          date: util.formatTime(new Date()).substring(0, 10),
          day: that.data.jcurDataDate.value || 0,
          agentId: wx.getStorageSync('userDo').id,
          offset:that.data.joffset,
          saleType: that.data.jcurDataType.id,
         
        },
        success:function(res){
          if (res.data.length) {
            var list = [];
            that.data.jiamemList ? list = that.data.jiamemList.concat(res.data) : list = res.data
            that.setData({
              jiamemList: list
            })
          } else {
            that.setData({
              noJm: true
            })
          }   
          that.setData({
            loading: false
          })            
        }
      })
    },
    lowerJm: function () {
      var page = this.data.joffset
      page++
      this.setData({
        joffset: page
      })
      this.getJiaMengList();
    },
    lowerRankings:function(){
        var page = this.data.offset
        page++
        this.setData({
            offset: page
        })
        this.getRankingsList();
    },

    lowerAnalysisList:function(){
        var page = this.data.offseta
        page++
        this.setData({
            offseta: page
        })
        this.getAnalysisList();
    },


    //获取排行列表
    getRankingsList:function(){
        var that = this;
        var user = wx.getStorageSync('userDo');
          that.setData({
            loading: true
        })
        wx.request({
            url: app.globalData.api + 'salesRankList',
            data: {
                time: that.data.curDataDate.value || 0,
                userTypee: user.type,
                makerUserId: user.userId,
                offset: that.data.offset,
                makerId: that.data.curDataCoffeeMaker.id || '',
                saleType: that.data.curDataType.id || '',
                sort: that.data.curRanking.id,
                leagueId: that.data.cjm.userId || -1 ,//默认自营
                font: wx.getStorageSync('userDo').font

            },
            success: function (res) {
                if (res.statusCode == 200) {
                    that.setData({
                        loading: false
                    })
                    if (res.data.length) {
                        var list = that.data.RankingsList
                        for (var i = 0; i < res.data.length; i++) {
                            list.push(res.data[i])
                        }
                        that.setData({
                            RankingsList: list,
                            noData: false
                        })
                    } else {
                        that.setData({
                            noData: true
                        })
                    }
                }
            }
        })
    },
    //获取时间筛选列表
    getDateList: function () {
        var that = this;
        wx.request({
            
            url: app.globalData.api + 'dictList/time_interval/' + wx.getStorageSync('userDo').font,
            success: function (res) {
                that.setData({
                    curDataDateList: res.data,
                    curDataDate: res.data[0],
                    jcurDataDateList: res.data,
                    jcurDataDate: res.data[0]
                })
            }
        })
    },

    //获取咖啡机筛选列表
    getCoffeeMakerList: function (duser) {
        var that = this;
        var user ={}
      
        user = duser;
 
     
        return new Promise((resolve,reject) =>{
          wx.request({
            url: app.globalData.api + 'getMakerListByUserIdNoPage',
            data: {
              type: user.type < 0 ? wx.getStorageSync('userDo').type : user.type,
              userId: user.type < 0 ? wx.getStorageSync('userDo').userId : user.userId,
              leagueNull: user.userId != -1 ? 0 : (wx.getStorageSync('userDo').type == 1 ?-1 :0)
            },
            success: function (res) {
              if(res){
                resolve(res.data)
              }else{
                reject(res.data)
              }
            }
          })
        })    
    },


    initData: function () {
        var dataTypes = [
            { id: '', name: '全部' },
            { id: 1, name: '咖啡' },
            { id: 2, name: '商品' }
        ]
        var dataRankings = [
            { id:1, name: '订单量排序' },
            { id:2,name:'销售额排序' }
        ]
        this.getDateList();

        var that = this;

       
        this.getJmList()
          .then(function (res) {  //获取加盟商筛选列表
            that.setData({
              jmList: res,
              cjm: res[0],
            })
            return that.getCoffeeMakerList(that.data.cjm)
          })
          .then(function (res) { //获取咖啡机筛选列表

            that.setData({
              curDataCoffeeMakerList: res,
              curDataCoffeeMaker: res[0],
            })

          })
       
        this.setData({
            curDataTypeList: dataTypes,
            curDataType: dataTypes[0],
            curRankingsList: dataRankings,
            curRanking: dataRankings[0],

            jcurDataTypeList: dataTypes,
            jcurDataType: dataTypes[0],
            jcurRankingsList: dataRankings,
            jcurRanking: dataRankings[0]

        })

        this.getRankingsList();
    }
    ,
    //获取月度统计列表
    getAnalysisList:function(){
        var that = this;
        var user = wx.getStorageSync('userDo');
        that.setData({
            loading: true
        })
        wx.request({
            url: app.globalData.api + 'coffeeOrderCountList',
            data: {
                makerUserId: user.userId,
                userTypee: user.type,
                offset: that.data.offseta,
                type: 2
            },
            success: function (res) {
                    that.setData({
                        loading: false
                    })
                    if (res.statusCode == 200) {
                        var list = that.data.AnalysisList
                        for (var i = 0; i < res.data.length; i++) {
                            list.push(res.data[i])
                        }
                        that.setData({
                            AnalysisList: list
                        })
                    }
              
               
            }
        })
    }


})